const db = require('../config/database');

class News {
    static async create({ title, content, category, reporter_name, image_url }) {
        const [result] = await db.query(
            'INSERT INTO news (title, content, category, reporter_name, image_url) VALUES (?, ?, ?, ?, ?)',
            [title, content, category, reporter_name, image_url]
        );
        return {
            news_id: result.insertId,
            title,
            content,
            category,
            reporter_name,
            image_url
        };
    }

    static async update(id, { title, content, category, reporter_name, image_url }) {
        await db.query(
            'UPDATE news SET title = ?, content = ?, category = ?, reporter_name = ?, image_url = ? WHERE news_id = ?',
            [title, content, category, reporter_name, image_url, id]
        );
        return {
            news_id: id,
            title,
            content,
            category,
            reporter_name,
            image_url
        };
    }

    static async getById(id) {
        const [rows] = await db.query(
            'SELECT * FROM news WHERE news_id = ?',
            [id]
        );
        return rows[0] || null;
    }

    static async getAll(page = 1, limit = 10, category, search) {
        let sql = 'SELECT * FROM news WHERE 1=1';
        const params = [];
        if (category) {
            sql += ' AND category = ?';
            params.push(category);
        }
        if (search) {
            sql += ' AND (title LIKE ? OR content LIKE ?)';
            params.push(`%${search}%`, `%${search}%`);
        }
        sql += ' ORDER BY publish_time DESC LIMIT ? OFFSET ?';
        params.push(Number(limit), Number((page - 1) * limit));
        const [rows] = await db.query(sql, params);
        return rows;
    }

    static async getTotal(category, search) {
        let sql = 'SELECT COUNT(*) as total FROM news WHERE 1=1';
        const params = [];
        if (category) {
            sql += ' AND category = ?';
            params.push(category);
        }
        if (search) {
            sql += ' AND (title LIKE ? OR content LIKE ?)';
            params.push(`%${search}%`, `%${search}%`);
        }
        const [rows] = await db.query(sql, params);
        return rows[0].total;
    }

    static async delete(id) {
        await db.query('DELETE FROM news WHERE news_id = ?', [id]);
    }

    static async incrementViews(id) {
        await db.query('UPDATE news SET read_count = read_count + 1 WHERE news_id = ?', [id]);
    }
}

module.exports = News; 